<?php
include_once 'db_env.php';

const IS_DEBUG = false;

$post = json_decode(file_get_contents('php://input'));
$user = isset($post) ? $post->user : null;
$payload = isset($post->payload) ? $post->payload : null;

function json_stringify($obj) {
  return json_encode($obj, JSON_UNESCAPED_UNICODE);
}

function log_text($text) {
  $file_name = '[log][' . date('Y-m-d') . '].txt';
  $phpself = $_SERVER['PHP_SELF'];
  $timestr = date('Y-m-d H:i:s');
  file_put_contents($file_name, "[{$timestr}][{$phpself}]\n{$text}\n\n", FILE_APPEND);
}

function log_sql($text) {
  if (strpos($text, 'INSERT') !== false || strpos($text, 'UPDATE') !== false) {
    $file_name = '[sql][' . date('Y-m-d') . '].txt';
    $phpself = $_SERVER['PHP_SELF'];
    $timestr = date('Y-m-d H:i:s');
    file_put_contents($file_name, "[{$timestr}][{$phpself}]\n{$text}\n\n", FILE_APPEND);
  }
}

function output($source, $ignore = false) {
  if ($source != null && $ignore == false) {
    $output = json_encode($source, JSON_UNESCAPED_UNICODE);
    echo $output;
    if (IS_DEBUG) {
      log_text($output);
    }
  }
}

function login($userstring, $userpasswd) {
  $sql = '';
  if (is_numeric($userstring)) {
    $userstring2 = $userstring . '';
    $userstring2 = substr($userstring2, 0, 4) . substr($userstring2, strlen($userstring) - 3, 3);
    $sql = "SELECT * FROM `oprec_security_data` WHERE (`number` = {$userstring} OR `number` = {$userstring2}) AND `disposed` = 0";
  } else {
    $sql = "SELECT * FROM `oprec_security_data` WHERE `name` = '{$userstring}' AND `disposed` = 0";
  }
  $res = exec_sql($sql);

  if (IS_DEBUG) {
    log_text(var_export($res, true));
  }

  $status = -1;
  $userbase = null;
  $userinfo = null;
  if ($res && count($res) == 1) {
    if ($res[0]['passwd'] == $userpasswd) {
      $status = 0;
      $userbase = array(
        'name' => $res[0]['name'],
        'number' => (int)$res[0]['number'],
        'passwd' => $res[0]['passwd'],
        'level' => (int)$res[0]['TREX_LEVEL'],
      );
      $userinfo = $res[0];
    } else {
      $status = 2;
    }
  } else {
    $status = 1;
  }
  $result = array(
    'status' => $status,
    'userbase' => $userbase,
    'userinfo' => $userinfo,
  );
  return $result;
}

function exec_sql($sql) {
  log_sql($sql);
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
  if ($con->connect_error) {
    log_text("连接失败: " . $con->connect_error);
    return null;
  }
  $con->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
  $result = $con->query($sql);
  if ($result) {
    if ($result->num_rows > 0) {
      $output_data = array();
      while ($row = $result->fetch_assoc()) {
        array_push($output_data, $row);
      }
      return $output_data;
    } elseif (is_bool($result)) {
      return $result;
    }
    return false;
  } else {
    return false;
  }
}

function exec_sql_array($sql_arr) {
  log_sql(implode("\n", $sql_arr));
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
  if ($con->connect_error) {
    log_text("连接失败: " . $con->connect_error);
    return null;
  }
  $con->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
  $results = array();
  foreach ($sql_arr as $sql) {
    $result = $con->query($sql . ';');
    array_push($results, $result);
  }
  return $results;
}